package org.zheng.shop.repository;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.zheng.shop.entity.CompanyNews;

import java.util.List;

/**
 * 企业动态Repository
 */
@Repository
public interface CompanyNewsRepository extends JpaRepository<CompanyNews, Long> {
    
    /**
     * 查找所有可见的动态，按置顶和发布时间排序
     */
    @Query("SELECT n FROM CompanyNews n WHERE n.isVisible = true ORDER BY n.isPinned DESC, n.publishedAt DESC")
    Page<CompanyNews> findVisibleNews(Pageable pageable);
    
    /**
     * 查找所有可见的动态列表（不分页）
     */
    @Query("SELECT n FROM CompanyNews n WHERE n.isVisible = true ORDER BY n.isPinned DESC, n.publishedAt DESC")
    List<CompanyNews> findVisibleNewsList();
    
    /**
     * 查找所有动态，按创建时间倒序
     */
    Page<CompanyNews> findAllByOrderByCreatedAtDesc(Pageable pageable);
    
    /**
     * 根据标题搜索可见的动态
     */
    @Query("SELECT n FROM CompanyNews n WHERE n.isVisible = true AND n.title LIKE %:keyword% ORDER BY n.isPinned DESC, n.publishedAt DESC")
    Page<CompanyNews> searchVisibleNewsByTitle(@Param("keyword") String keyword, Pageable pageable);
    
    /**
     * 根据标题搜索所有动态（管理员用）
     */
    @Query("SELECT n FROM CompanyNews n WHERE n.title LIKE %:keyword% ORDER BY n.createdAt DESC")
    Page<CompanyNews> searchAllNewsByTitle(@Param("keyword") String keyword, Pageable pageable);
    
    /**
     * 增加浏览次数
     */
    @Modifying
    @Query("UPDATE CompanyNews n SET n.viewCount = n.viewCount + 1 WHERE n.id = :id")
    void incrementViewCount(@Param("id") Long id);
    
    /**
     * 获取置顶的可见动态
     */
    @Query("SELECT n FROM CompanyNews n WHERE n.isVisible = true AND n.isPinned = true ORDER BY n.publishedAt DESC")
    List<CompanyNews> findPinnedVisibleNews();
    
    /**
     * 获取最新的几条可见动态
     */
    @Query("SELECT n FROM CompanyNews n WHERE n.isVisible = true ORDER BY n.publishedAt DESC")
    List<CompanyNews> findLatestVisibleNews(Pageable pageable);
}
